package com.ruoyi.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.ChannelEnum;
import com.ruoyi.common.exception.BusiException;
import com.ruoyi.common.exception.NoticeException;
import com.ruoyi.system.domain.Bank;
import com.ruoyi.system.domain.Cash;
import com.ruoyi.system.domain.Order;
import com.ruoyi.system.mapper.BankMapper;
import com.ruoyi.system.service.*;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BankServiceImpl extends BaseServiceImpl<BankMapper, Bank> implements BankService {


    @Resource
    private CashService cashService;
    @Lazy
    @Resource
    private OrderService orderService;

    @Resource
    private RedisCache redisCache;

    @Resource
    private ISysUserService userService;

    @Override
    public Bank getRand(BigDecimal amount, String channelCode) {
        return getRand(amount, channelCode, null);
    }

    @Override
    public Bank getRand(BigDecimal amount, String channelCode, BigDecimal limitAmount) {
        SysUser sysUser = new SysUser();
        sysUser.setJumpStatus(1);
        int count = userService.countByDomain(sysUser);
        List<Bank> banks;
        Integer jumpStatus = null;
        if (count > 0) {
            jumpStatus = 1;
        }
        banks = this.baseMapper.listBank(amount, channelCode, jumpStatus, limitAmount);
        ChannelEnum channelEnum = ChannelEnum.getChannelEnum(channelCode);

        if (CollectionUtil.isEmpty(banks)) {

            throw new NoticeException("通道: " + channelEnum.getName() + ",无接收账号");
        }

        if (banks.size() == 1) {
            return banks.get(0);
        }
        //拿出所有用户id
        List<Long> userIds = banks.stream().map(b -> b.getUserId()).collect(Collectors.toList());

        for (int i = 0; i < banks.size(); i++) {
            userIds.add(banks.get(i).getUserId());
        }
        userIds = CollectionUtil.distinct(userIds);

        List<Long> redisCacheCacheList = redisCache.getCacheList("bank_userId");
        if (CollectionUtil.isEmpty(redisCacheCacheList)) {
            redisCache.setCacheList("bank_userId", userIds);
            redisCacheCacheList = userIds;
        }

        Long userId;
        while (true) {
            //如果不是空的 取出第一个
            userId = redisCacheCacheList.get(0);
            if (CollectionUtil.contains(userIds, userId)) {//如果该用户可以接单
                redisCacheCacheList.remove(userId);
                redisCache.deleteObject("bank_userId");
                if (CollectionUtil.isNotEmpty(redisCacheCacheList)) {
                    redisCache.setCacheList("bank_userId", redisCacheCacheList);
                }
                break;
            }
            if (!CollectionUtil.contains(userIds, userId)) {//如果该用户已关闭接单
                redisCacheCacheList.remove(userId);
                if (CollectionUtil.isEmpty(redisCacheCacheList)) {

                    userId = userIds.get(0);
                    userIds.remove(userId);
                    redisCache.deleteObject("bank_userId");
                    if (CollectionUtil.isNotEmpty(userIds)) {
                        redisCache.setCacheList("bank_userId", userIds);
                    }

                    break;
                }
            }


        }


        return getByUserId(banks, userId);

    }

    private Bank getByUserId(List<Bank> banks, Long userId) {
        for (int i = 0; i < banks.size(); i++) {
            if (userId.equals(banks.get(i).getUserId())) {
                return banks.get(i);
            }
        }
        return null;

    }

    @Override
    public Bank getUserBank(Long userId, BigDecimal amount, String channelCode) {

        Cash cash = cashService.getByUserId(userId);
        if ((cash.getEarning().subtract(new BigDecimal(1000)).compareTo(amount) < 0)) {
            throw new BusiException("余额不足");
        }

        SysUser sysUser = new SysUser();
        sysUser.setJumpStatus(1);
        int count = userService.countByDomain(sysUser);

        Integer jumpStatus = null;
        if (count > 0) {
            jumpStatus = 1;
        }

        List<Bank> banks = this.baseMapper.listUserBank(userId, amount, channelCode, jumpStatus);
        if (CollectionUtil.isEmpty(banks)) {
            throw new NoticeException("通道: " + ChannelEnum.getName(channelCode) + ",无接收账号");
        }

        int i = RandomUtil.randomInt(banks.size());
        Bank bank = banks.get(i);

        return bank;
    }

    @Override
    protected void setQuery(QueryWrapper<Bank> query) {
//        query.groupBy("username", "id");
//        query.orderByDesc("id");
        super.setQuery(query);
    }

    //获取最新的单子
    private List<Order> getLastest() {
        Order order = new Order();
//        order.setChannelCode(ChannelEnum.SZ_RMB.getCode());
        PageDomain pageDomain = new PageDomain();
        pageDomain.setPageSize(15);
        List<Order> list = orderService.findList(order, pageDomain);
        return list;
    }

    private boolean exist(List<Order> list, Long userId) {
        for (int i = 0; i < list.size(); i++) {
            Order order = list.get(i);
            if (userId.equals(order.getUserId())) {
                return true;
            }
        }
        return false;

    }
}
